package com.biovr.backend.restcontroller;

import com.biovr.backend.domain.*;
import com.biovr.backend.domain.System;
import com.biovr.backend.repository.*;
import com.biovr.backend.utils.ResponseFactory;
import com.biovr.backend.utils.RestResponse;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * Created by monodev on 2017/5/9.
 */
@Api(value = "/systems",description = "系统API", consumes="application/json")
@RestController
@RequestMapping("/systems")
public class SystemRestController {
    @Autowired
    SystemRepository systemRepository;
    @Autowired
    ExpirementRepository expirementRepository;
    @Autowired
    ApparatusRepository apparatusRepository;
    @Autowired
    UserRepository userRepository;
    @Autowired
    ReagentRepository reagentRepository;
    @Autowired
    SchoolRepository schoolRepository;
    @Autowired
    PublishMessageReposiory publishMessageReposiory;

    /**
     * 获得系统信息
     * 始终只返回一条信息
     * @return
     */
    @ApiOperation(value="获得系统信息",response = RestResponse.class)
    @GetMapping
    public RestResponse<System> getAllSystemInfo(){
        List<System> systems = systemRepository.findAll();
        if(null==systems||systems.size()==0){
            systems.add(new System());
        }
        System system =systems.get(0);
        if(system!=null){
            system.setExpmCount( expirementRepository.count());
            system.setApparatusCount( apparatusRepository.count());
            system.setReagentCount( reagentRepository.count());
            system.setUserCount( userRepository.count());
            system.setSchoolCount( schoolRepository.count());
            system.setPushCount(publishMessageReposiory.count());
        }
        return ResponseFactory.createRestResponse(true,"",system);
    }

    /**
     * 添加/修改系统信息
     * @param system
     * @return
     */
    @PostMapping
    @ApiImplicitParam(name = "system", value = "系统对象", required = true, dataType = "System")
    public RestResponse<System> add(@RequestBody System system) throws Exception{

        if ( system.getId()==null||system.getId().equals("")){
            List<System> systems = systemRepository.findAll();
            if(null!=systems||systems.size()>0){
                return ResponseFactory.createErrorResult("系统表只能有一条记录");
            }
        }
        else {
            System tarSystem =  systemRepository.findOne(system.getId());
            if(tarSystem!=null){
                return ResponseFactory.createSuccessResult(systemRepository.save(system));
            }
            else{
                return ResponseFactory.createErrorResult("系统表中找不到数据");
            }
        }
        return ResponseFactory.createErrorResult("系统表只能有一条记录");

    }

}
